<template>
  <view class="tagSetting-page">
    <tb-tabs :tabList="tabList" v-model="activeName"> </tb-tabs>
    <view class="tag-selected">
      <view class="tips">分类可点击修改</view>
      <ul class="tag-content tag-content__selected">
        <li
          class="tag-item"
          v-for="(tag, index) in tagSelectdNoDelList"
          :key="index"
        >
          <view
            class="tag-icon"
            :style="{ background: tag.iconColor || '#87cefa' }"
          >
            <i
              :class="['icon', 'iconfont', tag.icon]"
              @click="onClickEditTag(tag, index)"
            ></i>
            <view class="delete" @click="onDelTag(tag)"></view>
          </view>
          <span class="tag-name">{{ tag.name }}</span>
        </li>
      </ul>
    </view>
    <view class="tag-template tag-category">
      <view class="tag-category-header">
        <span class="tag-category-title">
          <i class="icon iconfont icon-fenlei"></i>
          添加模板分类
        </span>
        <span class="book-template">
          <picker
            @change="handleChangeTemplate"
            :value="index"
            :range="templateList"
            range-key="tempName"
            mode="selector"
          >
            <view class="uni-input"
              >{{
                templateList[index] && templateList[index].tempName
              }}模板</view
            >
          </picker>
        </span>
      </view>
      <ul class="tag-content" v-if="tempTagList.length">
        <li
          class="tag-item"
          v-for="(tag, index) in tempTagList"
          :key="index"
          @click="onClickCategoryTag(tag)"
        >
          <view
            class="tag-icon"
            :style="{ background: tag.iconColor || '#87cefa' }"
          >
            <i :class="['icon', 'iconfont', tag.icon]"></i>
          </view>
          <span class="tag-name">{{ tag.name }}</span>
        </li>
      </ul>
      <view class="empty-text" v-else>暂无更多分类</view>
    </view>
    <view class="tag-custom tag-category">
      <view class="tag-category-header">
        <span class="tag-category-title" @click="onClickAddCustomTag">
          <i class="icon iconfont icon-jiahao"></i>
          添加自定义分类
        </span>
      </view>
    </view>
  </view>
</template>
<script lang="ts">
import { booksTemplateItem, tag } from '@/type/books'
import { handleCompareToRepeat } from '@/utils/tool'
import Vue from 'vue'
import { mapState } from 'vuex'

export default Vue.extend({
  data() {
    return {
      activeName: '支出',
      tempActiveName: '', // 用于刷新页面 触发watch监听activeName
      tabList: [
        { label: '支出', name: '支出' },
        { label: '收入', name: '收入' },
      ],
      // 当前activeName类型 选中标签，包含opterateType=3的标签
      tagSelectdList: [] as tag[],
      // 当前activeName类型 选中标签，不包含opterateType=3的标签
      tagSelectdNoDelList: [] as tag[],
      // 非当前activeName类型 选中标签
      tagOtherTypeSelectdList: [] as tag[],
      params: {
        pageSize: 10,
        pageNum: 1,
      },
      // 全部账本模板列表
      templateList: [] as booksTemplateItem[],
      index: 0, // 选中模板下标
      // 选中模板全部标签-收入/支出
      templateTagList: [] as tag[],
      // 选中模板中未被选中的标签
      tempTagList: [] as tag[],
      from: '', // 页面来源
    }
  },
  computed: {
    ...mapState('books', ['bookInfo']),
  },
  watch: {
    activeName: {
      handler(newVal, oldVal) {
        const tagListKey = this.from ? 'tagVOList' : 'tagList'
        this.tagSelectdList = this.bookInfo[tagListKey].filter(
          (tag: tag) => tag.type === newVal
        )
        this.tagOtherTypeSelectdList = this.bookInfo.tagList.filter(
          (tag: tag) => tag.type !== newVal
        )
        this.templateTagList = this.templateList[this.index]
          ? this.templateList[this.index].tagList.filter(
              (tag: tag) => tag.type === newVal
            )
          : []
        this.tempTagList = handleCompareToRepeat(
          this.tagSelectdList,
          this.templateTagList,
          'name'
        )['noTargetArr']
      },
      immediate: true,
    },
    tagSelectdList: {
      handler(newList, oldList) {
        this.tagSelectdNoDelList = newList.filter(
          (tag: tag) => tag.operateType !== 3
        )
        this.tempTagList = handleCompareToRepeat(
          this.tagSelectdNoDelList,
          this.templateTagList,
          'name'
        )['noTargetArr']
        // this.tempTagList.push(tag)
        this.$store.commit(
          'books/SET_TAGLIST',
          this.tagSelectdList.concat(this.tagOtherTypeSelectdList)
        )
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 删除标签
    onDelTag(tag: tag) {
      if (this.tagSelectdNoDelList.length === 1) {
        uni.showToast({ title: '请至少保留一个分类', icon: 'none' })
        return
      }
      this.$confirm(`确定删除 “${tag.name}” 分类吗`, '删除分类', {
        confirmText: '确定',
        cancelText: '取消',
        onConfirm: () => {
          /**
           * 新增账本时，直接删除
           * 编辑账本时，对比原始数据中是否有本标签，若有，标记本标签operateType=3，若没有，删除
           * 对比模板标签中是否有本标签，若有,且tempTagList没有同名标签则添加本标签至 tempTagList
           *
           * 从保存记录页面过来的即 from=record
           *  - 调用删除接口删除
           */
          const tagNameList = this.bookInfo.tagVOList.map(
            (item: tag) => item.name
          )
          if (this.bookInfo.id && tagNameList.includes(tag.name)) {
            this.tagSelectdList.forEach((item: tag) => {
              if (item.name === tag.name) {
                item.operateType = 3
              }
            })
            if (this.from === 'record') {
              /**  从保存记录页面过来的即 from=record
               *  - 调用删除接口删除
               * */
              this.$api.delTagsApi(null, tag.id).then(() => {
                console.log('success')
                this.tagSelectdList = this.tagSelectdList.filter(
                  (item: tag) => item.name !== tag.name
                )
              })
            }
          } else {
            this.tagSelectdList = this.tagSelectdList.filter(
              (item: tag) => item.name !== tag.name
            )
          }
        },
        onCancel: () => {
          console.log(89)
        },
      })
    },
    // 获取默认模板
    getDefaultBookTemp() {
      this.$api.getDefaultBookTempApi(this.params).then((res: any) => {
        this.templateList = res.data.list
        this.templateTagList = res.data.list[this.index].tagList.filter(
          (tag: tag) => tag.type === this.activeName
        )
        this.tempTagList = handleCompareToRepeat(
          this.tagSelectdNoDelList,
          this.templateTagList,
          'name'
        )['noTargetArr']
      })
    },
    // 切换模板分类
    handleChangeTemplate(e: any) {
      this.index = e.target.value
      this.templateTagList = this.templateList[e.target.value].tagList.filter(
        (tag: tag) => tag.type === this.activeName
      )
      this.tempTagList = handleCompareToRepeat(
        this.tagSelectdNoDelList,
        this.templateTagList,
        'name'
      )['noTargetArr']
    },
    // 点击模板分类区标签-添加标签
    onClickCategoryTag(tag: tag) {
      /**
       * 新增账本时，全部已操作标签无重名，直接添加；有重名 return 已存在相同名称的分类
       * 编辑账本时
       *  -- 全部已操作标签有重名且operateType!==3 return 已存在相同名称的分类
       *  -- 全部已操作标签有重名且operateType===3 修改当前标签，并operateType=0
       *  -- 全部已操作标签无重名 push 标签 operateType = 1
       * 或
       * 全部已操作标签无重名 push 标签 operateType = 1
       * 全部已操作标签有重名
       *  --新增账本 return 已存在相同名称的分类
       *  --编辑账本
       *      -- operateType !== 3 return 已存在相同名称的分类
       *      -- operateType===3 修改当前标签，并operateType=1
       *
       * 从保存记录页面过来的即 from=record
       *  - 调用新增接口增加
       */

      const selectedTagNameList = [] as string[]
      let repateTag = {} as tag // 重名标签
      this.tagSelectdList.forEach((item: tag) => {
        selectedTagNameList.push(item.name)
        if (item.name === tag.name) {
          repateTag = { ...item }
        }
      })
      if (!selectedTagNameList.includes(tag.name)) {
        if (this.from === 'record') {
          // 从保存记录页面过来的即 from=record  调用新增接口增加
          const tagTemp = { ...tag }
          delete tagTemp.id
          delete tagTemp.defaultTag
          this.$api
            .postTagsApi({
              ...tagTemp,
              bookId: this.bookInfo.id,
            })
            .then((res: any) => {
              if (res.code === 1) {
                this.tagSelectdList.push({...res.data})
              }
            })
        }else{
          this.tagSelectdList.push({
            ...tag,
            operateType: 1,
          })
        }
      } else {
        if (this.bookInfo.id && repateTag.operateType === 3) {
          this.tagSelectdList = this.tagSelectdList.map((item: tag) => {
            if (item.name === tag.name) {
              item = { ...tag, operateType: 0 }
            }
            return item
          })
        } else {
          uni.showToast({ title: '已存在相同名称的分类', icon: 'none' })
          return
        }
      }
    },
    // 添加自定义标签
    onClickAddCustomTag() {
      uni.navigateTo({
        url: `/pages/tag/index?type=${this.activeName}&index=${-2}&from=${this.from}`,
      })
    },
    // 编辑标签
    onClickEditTag(tag: tag, index: number) {
      uni.navigateTo({
        url: `/pages/tag/index?type=${this.activeName}&tagName=${tag.name}&index=${index}&from=${this.from}`,
      })
    },
    load() {
      this.activeName = this.tempActiveName || '支出'
      this.getDefaultBookTemp()
    },
  },
  onLoad(option: any) {
    option.activeName && (this.tempActiveName = option.activeName)
    option.from && (this.from = option.from)
  },
  onShow() {
    this.activeName = this.tempActiveName || '支出'
    this.getDefaultBookTemp()
  },
  onHide() {
    this.tempActiveName = this.activeName
    this.activeName = ''
    console.log('hide')
  },
})
</script>
<style lang="less" scoped>
.tagSetting-page {
  padding: 0 48rpx;
  .tag-selected {
    margin-top: 20rpx;
  }
  .tips {
    font-size: 28rpx;
    color: #ccc;
    text-align: center;
  }
}
.tag-content {
  margin-top: 30rpx;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(5, 20%);
  justify-items: center;
  align-items: center;
  grid-row-gap: 40rpx;
  .tag-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    .tag-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 20rpx;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10rpx;
      position: relative;
      .iconfont {
        font-size: 48rpx;
      }
      .delete {
        width: 30rpx;
        height: 30rpx;
        background: #e0e0e0;
        border-radius: 50%;
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        &::after {
          content: '';
          width: 16rpx;
          height: 4rpx;
          background: #fff;
          border-radius: 4rpx;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
    .tag-name {
      font-size: 24rpx;
      color: #333;
    }
  }
}
.tag-category {
  margin-top: 50rpx;
  .tag-category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tag-category-title {
      font-size: 28rpx;
      color: #333;
      .iconfont {
        color: #87cefa;
        margin-right: 20rpx;
        font-size: 28rpx;
      }
    }
    .book-template {
      font-size: 26rpx;
      color: #666;
      position: relative;
      padding-right: 30rpx;
      &::after {
        position: absolute;
        content: '';
        right: 0;
        top: 50%;
        border: solid #666;
        border-width: 0 2rpx 2rpx 0;
        display: inline-block;
        padding: 6rpx;
        transform: translateY(-75%) rotate(45deg);
      }
    }
  }
  .empty-text {
    text-align: center;
    font-size: 28rpx;
    color: #999;
    margin-top: 30rpx;
  }
}
</style>
